package com.quasar.hpatient.view.record;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.change360.calendarview.CalendarDay;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.quasar.hpatient.MainAppliaction;


import com.quasar.hpatient.R;
import com.quasar.hpatient.base.BaseActivity;
import com.quasar.hpatient.choicePhoto.PhotoSelectorActivity;
import com.quasar.hpatient.constant.ConstantManger;
import com.quasar.hpatient.model.controllermodel.PictureConstant;
import com.quasar.hpatient.model.custommodel.InspactionBean;
import com.quasar.hpatient.model.custommodel.InspactionitemBean;
import com.quasar.hpatient.model.custommodel.PhotoModel;
import com.quasar.hpatient.model.event.TestUpdatePhoto;
import com.quasar.hpatient.model.event.UpdateEvent;
import com.quasar.hpatient.model.httpmodel.AnotherResult;
import com.quasar.hpatient.model.httpmodel.DataStateResult;
import com.quasar.hpatient.model.litePalmodel.DailyItemInfodb;
import com.quasar.hpatient.model.medicalmodel.DailyRecordDetailsData;
import com.quasar.hpatient.model.medicalmodel.DiagnosisData;
import com.quasar.hpatient.model.medicalmodel.DoctorEventData;
import com.quasar.hpatient.model.medicalmodel.DoctorListBean;
import com.quasar.hpatient.model.medicalmodel.PatientInfoData;
import com.quasar.hpatient.model.medicalmodel.TestRecordData;
import com.quasar.hpatient.network.RetrofitConnection;
import com.quasar.hpatient.onInterface.AnotherResultListener;
import com.quasar.hpatient.onInterface.OnDailyMoreListener;
import com.quasar.hpatient.onInterface.OnDateChangedEvent;
import com.quasar.hpatient.onInterface.OnDoctorEventListener;
import com.quasar.hpatient.onInterface.viewInterface.UiInterface;
import com.quasar.hpatient.presenter.DailyMorePresenter;
import com.quasar.hpatient.presenter.DeleteGetRecentDiagnosePresenter;
import com.quasar.hpatient.presenter.DiagnosisDataPresenter;
import com.quasar.hpatient.presenter.DoctorEventPresenter;
import com.quasar.hpatient.presenter.TestRecordInitPresenter;
import com.quasar.hpatient.presenter.TestRecordPresenter;
import com.quasar.hpatient.utils.OutliersValues;
import com.quasar.hpatient.utils.Spanny;
import com.quasar.hpatient.utils.StringUtils;
import com.quasar.hpatient.utils.TimeZoneUtil;
import com.quasar.hpatient.view.AssayLinActivity_;
import com.quasar.hpatient.view.ImageViewpageActivity_;
import com.quasar.hpatient.view.adapter.TestGrideViewAdapter;
import com.quasar.hpatient.view.adapter.TestrecordsItemAdapter;
import com.quasar.hpatient.view.prescription.HistoryLifeActivity_;
import com.quasar.hpatient.view.viewInterface.ViewAnotherResultListener;
import com.quasar.hpatient.widget.ChoiceDoctorxDialog;
import com.quasar.hpatient.widget.WidgetDateTestRecordQuery;
import com.quasar.hpatient.widget.WidgetSymptoms;
import com.rey.material.app.Dialog;
import com.rey.material.app.DialogFragment;
import com.rey.material.app.SimpleDialog;
import com.vise.log.ViseLog;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.OptionsItem;
import org.androidannotations.annotations.OptionsMenu;
import org.androidannotations.annotations.ViewById;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

import me.iwf.photopicker.PhotoPicker;

/**
 * 化验报告
 */
@OptionsMenu(R.menu.menu_add_event)
@EActivity(R.layout.activity_test_record)
public class TestRecordActivity extends BaseActivity implements OnDateChangedEvent,
        TestrecordsItemAdapter.OnItemEditTextChangedListener, PictureConstant.updateUiInit, ViewAnotherResultListener, ChoiceDoctorxDialog.OnCustomDialogDetermineListener,
        OnDoctorEventListener, OnDailyMoreListener, AnotherResultListener<List<InspactionBean>> {

    // TODO: 2018/3/22
    // 是否修改数据
    boolean isModify = false;


    Diagnosis diagnosis;
    //获取诊断消息
    private DiagnosisDataPresenter diagnosisDataPresenter;
    private TestRecordPresenter testRecordPresenter;
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    //初始化化验单
    TestRecordInitDay testRecordInitDay;
    private static TestGrideViewAdapter testGrideViewAdapter;
    private TestrecordsItemAdapter itemAdapter;
    //将图片集合设置为static便于浏览界面调用
    public static ArrayList<String> photos = new ArrayList<>();
    //保存当如化验单图片
    public static ArrayList<PhotoModel> minitDatas = new ArrayList();
    List<InspactionBean> mData = new ArrayList<>();
    //获取当日化验单图片  将图片集合设置为static便于浏览界面调用
    public static List<TestRecordData.PicListBean> picListBeen = new ArrayList<>();
    //判断是获取当日化验数据还是上一次或者下一次化验数据
    int statsTime;
    //获取当前时间
    String DataTime = format.format(new Date());
    //图片上传
    PictureConstant pictureConstant;
    //图片提交地址
    String CorePhone;
    //判断大项名称是否为空
    String isTitleName;
    //医生添加的事件
    DoctorEventPresenter doctorEventPresenter;
    //查询日常记录信息
    DailyMorePresenter dailyMorePresenter;

    @ViewById(R.id.main_toolbar)
    Toolbar main_toolbar;
    @ViewById(R.id.rv_list)
    RecyclerView rv_list;
    //事件
    @ViewById(R.id.thisevent_list)
    LinearLayout thisevent_list;
    //诊断
    @ViewById(R.id.diagnosisbox)
    LinearLayout diagnosisbox;
    //医生名称
    @ViewById(R.id.doctorname)
    TextView doctorname;
    //诊断内容
    @ViewById(R.id.note)
    TextView note;
    @ViewById(R.id.loadingbox)
    ProgressBar loadingbox;
    //诊断图表
    @ViewById(R.id.stamp)
    ImageView stamp;
    //不适症状
    @ViewById(R.id.ws_describe)
    WidgetSymptoms ws_describe;
    //左右切换日期
    @ViewById(R.id.datequery)
    WidgetDateTestRecordQuery datequery;
    //日期传过来的数据
    @Extra
    String TestTime;

    DeleteGetRecentDiagnosePresenter deleteGetRecentDiagnosePresenter;

    //有诊断信息点击进入生命史
    @Click(R.id.tv_look_zhenduan)
    public void tv_look() {
        HistoryLifeActivity_.intent(this).start();
    }


    @AfterViews
    void init() {
        initView();
        initData();


        ViseLog.d("TestTime++++++++" + TestTime);
    }

    public static void notifyDataSetChanged() {
        testGrideViewAdapter.notifyDataSetChanged();
    }


    @Override
    protected void initView() {
        initToolbar();
        rv_list.setLayoutManager(new LinearLayoutManager(this));
        rv_list.setHasFixedSize(true);
        rv_list.setNestedScrollingEnabled(false);

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void initData() {

        testRecordPresenter = new TestRecordPresenter(TestRecordActivity.this);
        //先3获取数据库中化验单数据
        localData=new ArrayList<>();
        if (MainAppliaction.getInstance().getInspactionBeanListDB() == null) {
            testRecordPresenter.getDataTest();
        } else {
            localData.addAll(MainAppliaction.getInstance().getInspactionBeanListDB());

            for(int i=0;i<localData.size();i++){
                if(localData.get(i).getInspactionitemBeen()!=null){
                    localData.get(i).getInspactionitemBeen().setItemValue("");
                }
            }
            initViewData();
        }
    }

    //初始化数据
    public void initViewData() {
        pictureConstant = new PictureConstant(this);
        //如果是日期界面回传过来的数据则传入回传过来的日期，否则传入当前日期
        doctorEventPresenter = new DoctorEventPresenter(this);
        //查询当日日常记录
        dailyMorePresenter = new DailyMorePresenter(this);

        String timeDate;
        if (TestTime != null) {
            //隐藏日历跳转按钮
            datequery.hidesearch();
            timeDate = TestTime;
            datequery.setDate(timeDate);
        } else {
            TestTime = DataTime;
            timeDate = TestTime;
//            calendarDay = new CalendarDay();
//            datequery.setDate(calendarDay);
            datequery.setDate(timeDate);
        }

        //初始化当日日期
        datequery.setOnDateChangedEvent(this);

        //获取诊断内容
        diagnosis = new Diagnosis(timeDate);
        // ws_describe.setDate(timeDate);
        //获取单日化验单信息
        statsTime = 3;
        testRecordInitDay = new TestRecordInitDay(timeDate, statsTime);
        deleteGetRecentDiagnosePresenter = new DeleteGetRecentDiagnosePresenter(this);
    }


    public boolean chongfu() {

        boolean istest = true;
        List<InspactionitemBean> beanList = new ArrayList<>();
        for (int i = 0; i < itemAdapter.getData().size(); i++) {

            if (itemAdapter.getData().get(i).getItemType() == InspactionBean.FROM || itemAdapter.getData().get(i).getItemType() == InspactionBean.DIV_EDIT
                    || itemAdapter.getData().get(i).getItemType() == InspactionBean.PPOTEIN) {
                InspactionitemBean inspactionitemBean = itemAdapter.getData().get(i).getInspactionitemBeen();
                inspactionitemBean.setItemName(itemAdapter.getData().get(i).getInspactionitemBeen().getItemName());
                beanList.add(inspactionitemBean);
            }
        }

        for (int i = 0; i < beanList.size(); i++) {
            for (int j = beanList.size() - 1; j > i; j--) {
                if (beanList.get(i).getItemName().equals(beanList.get(j).getItemName())) {
                    msg("不能添加重复项目");
                    istest = false;
                }
            }
        }

        return istest;
    }


    //初始化adapter布局
    public void initAdapter(List<InspactionBean> data) {

        itemAdapter = new TestrecordsItemAdapter(data);
        rv_list.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

        TestName = new ArrayList<>();
        for (int i = 0; i < itemAdapter.getData().size(); i++) {
            if (itemAdapter.getData().get(i).getItemType() == 1) {
                TestName.add(itemAdapter.getData().get(i).getInspactionName());
            }
        }
        strings = new ArrayList<>();
        for (int i = 0; i < itemAdapter.getData().size(); i++) {
            if (itemAdapter.getData().get(i).getInspactionitemBeen() != null) {
                if (itemAdapter.getData().get(i).getInspactionitemBeen().getItemName() != null) {
                    strings.add(itemAdapter.getData().get(i).getInspactionitemBeen().getItemName());
                }
            }
        }

        itemAdapter.notifyDataSetChanged();
        //添加动画
//        itemAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_LEFT);
        AddHeadView();
        itemAdapter.setListener(this);
        addFootView();
        rv_list.setAdapter(itemAdapter);

        itemAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                //新增item数据
                switch (view.getId()) {
                    case R.id.additem:
                        itemAdapter.notifyDataSetChanged();

                        if (!chongfu()) {
                            msg("不能添加重复项目");
                            return;
                        }

                        InspactionBean testDataBean = itemAdapter.getData().get(position - 1);//(InspactionBean) adapter.getItem(position);
                        //检查单新增限制为必须一项添加完成后才能添加新项目
                        for (int i = 0; i < itemAdapter.getData().size(); i++) {
                            InspactionBean inspaction = itemAdapter.getData().get(i);
                            if (inspaction.getInspactionitemBeen() != null) {
                                if (inspaction.getInspactionitemBeen().getItemName() == null || inspaction.getInspactionitemBeen().getItemName().length() == 0) {
                                    msg("请填写" + inspaction.getInspactionitemBeen().getInspectionName() + "化验项目");
                                    return;
                                }
                            }
                        }

                        InspactionitemBean inspactionitemBean = new InspactionitemBean();
                        if (testDataBean.getInspactionitemBeen() != null) {
                            inspactionitemBean.setInspectionName(testDataBean.getInspactionitemBeen().getInspectionName());
                            inspactionitemBean.setOuterLayerItem(testDataBean.getInspactionitemBeen().getInspectionName());
                        } else {
                            inspactionitemBean.setInspectionName("");
                            inspactionitemBean.setOuterLayerItem("");
                        }

                        inspactionitemBean.setItemName("");
                        inspactionitemBean.setItemValue("");
                        inspactionitemBean.setStandardValue("");
                        inspactionitemBean.setDoseName("");
                        inspactionitemBean.setParamValue("");
                        inspactionitemBean.setId("");
                        inspactionitemBean.setAttribute(ConstantManger.CUSTOMVIEW);//位-1的时候位自定义非默认项
                        inspactionitemBean.setCriticalValue("");
                        Additem(position, new InspactionBean(InspactionBean.DIV_EDIT, inspactionitemBean));
                        break;

                    //移除非默认项
                    case R.id.edit_delete:
//
//                        if(!chongfu()){
//                            msg("不能添加重复项目");
//                            return;
//                        }

                        InspactionBean Bean = itemAdapter.getData().get(position);
                        if (Bean.getInspactionitemBeen().getAttribute() == ConstantManger.HIDEVIEW) {//位0时位默认项
                            Bean.getInspactionitemBeen().setIsHide("隐藏");
                            Bean.getInspactionitemBeen().setItemValue("");
                            itemAdapter.notifyDataSetChanged();
                        } else if (Bean.getInspactionitemBeen().getAttribute() == ConstantManger.CUSTOMVIEW) {//删除自定义非默认项目
                            itemAdapter.remove(position);
                            itemAdapter.notifyDataSetChanged();
                            itemAdapter.notifyItemRangeRemoved(position, itemAdapter.getData().size() - position);
                            deleteGetRecentDiagnosePresenter.DeleteGetRecentDiagnoseData(Bean.getInspactionitemBeen().getId());
                        }
                        break;

                    case R.id.edit_delete1:
                        itemAdapter.notifyDataSetChanged();

                        itemAdapter.getData().remove(position);
                        itemAdapter.notifyItemRangeRemoved(position, itemAdapter.getData().size() - position);
                        break;
                    //点击分析折线图
                    case R.id.name:
                        AssayLinActivity_.intent(TestRecordActivity.this).ItemName(itemAdapter.getItem(position).getInspactionitemBeen().getItemName())
                                .ItemTime(datequery.getDate()).inspactionBean(itemAdapter.getItem(position)).start();
                        break;

                    case R.id.inspection_save:

                        itemAdapter.notifyDataSetChanged();
                        TestName = new ArrayList<>();
                        for (int i = 0; i < itemAdapter.getData().size(); i++) {
                            if (itemAdapter.getData().get(i).getItemType() == 1) {
                                TestName.add(itemAdapter.getData().get(i).getInspactionName());
                            }
                        }
                        Boolean issubmit = false;
                        if (isTitleName != null && isTitleName.length() > 0) {

                            for (int a = 0; a < TestName.size(); a++) {
                                ViseLog.d("11111");
                                if (isTitleName.equals(TestName.get(a))) {
                                    issubmit = true;
                                }
                            }
                            if (issubmit) {
                                msg("化验单名称不能重复!");
                                return;
                            } else {
                                ViseLog.d("自定义的化验单名称的长度++++++++" + itemAdapter.getData().size());
                                ViseLog.d(isTitleName);

                                AddDivItem(position, new InspactionBean(InspactionBean.TITLE, isTitleName));
                                InspactionitemBean inspactionitemBean1 = new InspactionitemBean();
                                inspactionitemBean1.setInspectionName(isTitleName);
                                inspactionitemBean1.setItemValue("");
                                inspactionitemBean1.setStandardValue("");
                                inspactionitemBean1.setDoseName("");
                                inspactionitemBean1.setParamValue("");
                                inspactionitemBean1.setId("");
                                inspactionitemBean1.setAttribute(ConstantManger.CUSTOMVIEW);
                                inspactionitemBean1.setOuterLayerItem(isTitleName);
                                inspactionitemBean1.setCriticalValue("");
                                mData.add(new InspactionBean(InspactionBean.DIV_EDIT, inspactionitemBean1));
                                mData.add(new InspactionBean(InspactionBean.EDIT, true));
                                itemAdapter.notifyDataSetChanged();

                                ViseLog.d("自定义的化验单名称的长度---------" + isTitleName);
//                            itemAdapter.setData(position, mData);
                                testname = false;
                            }
                        } else {
                            msg("化验单名称不能为空!");
                        }
                        break;

                    case R.id.closelist://折叠
                        setViewGone(position, "隐藏");
                        break;


                    case R.id.all://展开
                        setViewGone(position, "");
                        break;


//                    case R.id.closelist://折叠
//                        TextView textView = (TextView) view.findViewById(R.id.closelist);
//                        if(isButton){
//                            textView.setText("展开");
//                            setViewGone(position, "隐藏");
//                            isButton=false;
//                        }else{
//                            textView.setText("隐藏");
//                            setViewGone(position, "");
//                            isButton=true;
//                        }
//                        break;
////                    case R.id.all://展开
////                        setViewGone(position, "");
////                        break;
                }
            }
        });


    }

    //    //获取集合中ParamValue自大值
    public Integer paramValueMaxValues() {
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < mData.size(); i++) {
            if (mData.get(i).getInspactionitemBeen() != null) {
                if (mData.get(i).getInspactionitemBeen().getParamValue() != null) {
                    list.add(Integer.parseInt(mData.get(i).getInspactionitemBeen().getParamValue()));
                }
            }
        }
        return Collections.max(list);
    }

    List<String> TestName = new ArrayList<>();
    List<String> strings = new ArrayList<>();


    public void setViewGone(int position, String val) {
        InspactionBean foldTest = itemAdapter.getData().get(position);
        ViseLog.d("获取大项的名称" + foldTest.getInspactionName());
        // 获取全部数据
        List<InspactionBean> listInspaction = new ArrayList<>();
        listInspaction.addAll(itemAdapter.getData());

        for (int i = 0; i < listInspaction.size(); i++) {
            if (listInspaction.get(i).getInspactionitemBeen() != null) {
                if (listInspaction.get(i).getInspactionitemBeen().getOuterLayerItem().equals(foldTest.getInspactionName())) {
                    InspactionBean inspactionBean = listInspaction.get(i);
                    InspactionitemBean inspactionitemBean1 = inspactionBean.getInspactionitemBeen();

                    if (inspactionitemBean1.getAttribute() == ConstantManger.HIDEVIEW || inspactionitemBean1.getAttribute() == ConstantManger.CUSTOMVIEW) {//根据getAttribute数据判断默认项，进项显示隐藏0
                        //有数据的非默认项不能进行隐藏
                        if (inspactionitemBean1.getItemValue() != null && inspactionitemBean1.getItemValue().length() > 0) {
                            inspactionitemBean1.setIsHide("");
                        } else {
                            inspactionitemBean1.setIsHide(val);
                        }
                    }
                    inspactionBean.setInspactionitemBeen(inspactionitemBean1);

                    itemAdapter.getData().set(i, inspactionBean);
                }
            }

        }


        itemAdapter.notifyDataSetChanged();
    }


    //新增item数据
    public void Additem(int position, InspactionBean data) {//  List<InspactionBean> mData;
        itemAdapter.getData().add(position, data);

        itemAdapter.notifyItemInserted(position);//通知演示插入动画
        itemAdapter.notifyItemRangeChanged(position, itemAdapter.getData().size() - position);//通知数据与界面重新绑定
        itemAdapter.notifyDataSetChanged();
    }


    //添加事件
    @OptionsItem(R.id.menu_event)
    public void menu_event() {

        //跳转事件添加界面时要带当前选择的时间
        StringBuffer buffer = new StringBuffer();
        buffer.append(datequery.getDate());
        buffer.append(TimeZoneUtil.sdf.format(new Date()).substring(10, TimeZoneUtil.sdf.format(new Date()).length()));

        EventActivity_.intent(this).TimeDate(buffer.toString()).start();
    }

    boolean isClick = true;
    boolean errVal = true;

    //提交
    String json = null;

    //提交化验单
    @OptionsItem(R.id.action_submit)
    public void action_submit() {

        errVal = true;

        if (!chongfu()) {
            msg("不能添加重复项目");
            return;
        }

        //检查单新增限制为必须一项添加完成后才能添加新项目
        for (int i = 0; i < itemAdapter.getData().size(); i++) {
            InspactionBean inspaction = itemAdapter.getData().get(i);
            if (inspaction.getInspactionitemBeen() != null) {
                if (inspaction.getInspactionitemBeen().getItemName() == null || inspaction.getInspactionitemBeen().getItemName().length() == 0) {
                    msg("请填写" + inspaction.getInspactionitemBeen().getInspectionName() + "下的化验项目");
                    return;
                }
            }
        }

        TestName = new ArrayList<>();
        for (int i = 0; i < itemAdapter.getData().size(); i++) {
            if (itemAdapter.getData().get(i).getItemType() == 1) {
                TestName.add(itemAdapter.getData().get(i).getInspactionName());
            }
        }

        strings = new ArrayList<>();
        for (int i = 0; i < itemAdapter.getData().size(); i++) {
            if (itemAdapter.getData().get(i).getItemType() == 2) {
                strings.add(itemAdapter.getData().get(i).getInspactionitemBeen().getItemName());
            }
        }

        itemAdapter.nofocusable();

        datas = "";
        itemAdapter.test();

        boolean issubmit = false;
        boolean isxiaoname = false;
//        if (isTitleName != null && isTitleName.length() > 0) {
//
//            for (int a = 0; a < TestName.size(); a++) {
//                ViseLog.d("11111");
//                if (isTitleName.equals(TestName.get(a))) {
//                    issubmit = true;
//                }
//            }
//            if (issubmit) {
//                msg("化验单名称不能重复!");
//                return;
//            }
//        }

        if (testItmeVal != null && testItmeVal.length() > 0) {
            for (int a = 0; a < strings.size(); a++) {
                if (testItmeVal.equals(strings.get(a))) {
                    isxiaoname = true;
                    break;
                }
            }
            if (isxiaoname) {
                msg("化验项名称不能重复!");
                return;
            }
        }


        itemAdapter.notifyDataSetChanged();
        ViseLog.d("数据异常---" + errVal);
        List<InspactionitemBean> beanList = new ArrayList<>();
        for (int i = 0; i < itemAdapter.getData().size(); i++) {

            ViseLog.d("数据异常" + errVal);
            if (itemAdapter.getData().get(i).getItemType() == InspactionBean.FROM || itemAdapter.getData().get(i).getItemType() == InspactionBean.DIV_EDIT
                    || itemAdapter.getData().get(i).getItemType() == InspactionBean.PPOTEIN) {

                beanList.add(itemAdapter.getData().get(i).getInspactionitemBeen());

                if (errVal) {
                    ViseLog.d("数据异常****" + errVal);
                    if (itemAdapter.getData().get(i).getInspactionitemBeen().getItemValue() != null
                            && itemAdapter.getData().get(i).getInspactionitemBeen().getStandardValue() != null &&
                            !itemAdapter.getData().get(i).getInspactionitemBeen().getItemValue().equals("0") && itemAdapter.getData().get(i).getInspactionitemBeen().getItemValue().length() > 0) {
                        int stats = OutliersValues.TextColor(itemAdapter.getData().get(i).getInspactionitemBeen().getItemValue(), itemAdapter.getData().get(i).getInspactionitemBeen().getStandardValue());

                        ViseLog.d("数据是否异常" + stats + "---"
                                + itemAdapter.getData().get(i).getInspactionitemBeen().getItemValue() + "参考值" + itemAdapter.getData().get(i).getInspactionitemBeen().getStandardValue());
                        if (stats != 0) {
                            errVal = false;
                        }
                    }
                }
            }
        }


        for (int i = 0; i < beanList.size(); i++) {
            for (int j = beanList.size() - 1; j > i; j--) {
                if (beanList.get(i).getItemName().equals(beanList.get(j).getItemName())) {
                    msg("不能添加重复项目");
                    return;
                }
            }
        }

        boolean isValue = false;
        boolean isPhoto = false;

        for (int i = 0; i < beanList.size(); i++) {
            if (beanList.get(i).getItemValue().length() > 0) {
                isValue = true;
            }
        }


        //如果那个数据name为空则进行删除
        for (int i = 0; i < beanList.size(); i++) {
            if (beanList.get(i) != null) {
                if (beanList.get(i).getItemName().length() == 0 || beanList.get(i).getItemName() == null) {
//                    msg("检测项目不能为空");
                    beanList.remove(i);
//                    return;
                }
            }

        }
//
//        if(!isNameTimeVal){
//            msg("化验项目名称不能为空");
//            return;
//        }


        for (int i = 0; i < beanList.size(); i++) {
            beanList.get(i).setParamValue(i + "");
        }

        if (minitDatas.size() != 0) {
            isPhoto = true;
        }

        if (!isValue && !isPhoto) {
            msg("请填写化验数据");
            return;
        }


        ViseLog.d("提交的化验单数据长度为" + beanList.size());
        json = JSON.toJSONString(beanList);

        ViseLog.d("提交的化验单数据长度为" + json);


        Dialog.Builder builder = new SimpleDialog.Builder(R.style.SimpleDialogLight) {
            @Override
            public void onPositiveActionClicked(DialogFragment fragment) {
                super.onPositiveActionClicked(fragment);
                SubmitTestData();
            }

            @Override
            public void onNegativeActionClicked(DialogFragment fragment) {
                super.onNegativeActionClicked(fragment);
                String TimeData = datequery.getDate();
                dailyMorePresenter.GetPatientDailySingleRecords(TimeData);
            }
        };
        builder.title("是否提交给医生诊断")
                .positiveAction("否")
                .negativeAction("是");
        ((SimpleDialog.Builder) builder).message("");
        DialogFragment fragment = DialogFragment.newInstance(builder);

        if (this instanceof AppCompatActivity) {
            AppCompatActivity activity = this;
            fragment.show(activity.getSupportFragmentManager(), null);
        }
    }


    //提交化验单数据
    public void SubmitTestData() {
        //获取当前选中的时间
        StringBuffer buffer = new StringBuffer();
        buffer.append(datequery.getDate());
        buffer.append(" 00:00:00");
        //判断提交值是否存在异常
        if (isClick) {
            upPhotoPath();
            isClick = false;
            showDialog();
//            if(errVal){
//                deleteGetRecentDiagnosePresenter.PostRemindMedicine(json, buffer.toString(), Core, ConstantManger.NormalVal);
//            }else{
//                deleteGetRecentDiagnosePresenter.PostRemindMedicine(json, buffer.toString(), Core, ConstantManger.OutliersVal);
//            }
        }
    }


    //左右改变日期进行重新查询化验数据
    @Override
    public void onDateChanged(CalendarDay date) {
        //  ws_describe.setDate(format.format(date.getDate()));
        //获取单日化验单信息
        TestTime = null;

        String stats = datequery.getStatus();
        String TimeDate = datequery.getDate();

        if (stats.equals("1")) {
            statsTime = 1;
        } else if (stats.equals("2")) {
            statsTime = 2;
        }
        testRecordInitDay = new TestRecordInitDay(TimeDate, statsTime);
    }

    //获取保存的本地化验单数据
    List<InspactionBean> localData=null;

    //获取数据库中的化验单信息
    @Override
    public void onSuccess(List<InspactionBean> data) {
        localData.clear();
        localData.addAll(data);
        MainAppliaction.getInstance().setInspactionBeanListDB(data);
        initViewData();

    }

    @Override
    public void onError(String msg) {
        if (msg != null) {
            msg(msg);
        }
        dessDialog();
    }

    @Override
    public void onRefreshUI() {
        dessDialog();
        ViseLog.d("获取本地数据加载完成后执行");
    }


    //添加图片头布局

    public void AddHeadView() {

        for (int i = 0; i < minitDatas.size(); i++) {
            photos.add(minitDatas.get(i).getOriginalPath());
        }

        View viewhead = getLayoutInflater().inflate(R.layout.foot_view, (ViewGroup) rv_list.getParent(), false);
//        TextView tv_count_image= (TextView) viewhead.findViewById(R.id.tv_count_image);
//        Spanny spanny=new Spanny();
//        spanny.append("(", new ForegroundColorSpan(color(R.color.btcolor)));
//        spanny.append("上传检查单", new ForegroundColorSpan(color(R.color.red)));
//        spanny.append(")", new ForegroundColorSpan(color(R.color.btcolor)));
//        tv_count_image.setText(spanny);

        GridView gridView = (GridView) viewhead.findViewById(R.id.gridView);
        testGrideViewAdapter = new TestGrideViewAdapter(this, minitDatas);
        gridView.setAdapter(testGrideViewAdapter);

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == minitDatas.size()) {
                    selectPic();
                } else {
                    //跳转图片预览界面
                    //传递标识显示隐藏删除图片按钮
                    ImageViewpageActivity_.intent(TestRecordActivity.this).Photolist(photos).position(position).photoModelDatas(minitDatas).start();
                }

            }
        });
        itemAdapter.addHeaderView(viewhead);
    }

    //选择图片
    public void selectPic() {

        PhotoPicker.builder()
                .setPhotoCount(99)
                .setShowCamera(true)
                .setShowGif(true)
                .setPreviewEnabled(false)
                .start(TestRecordActivity.this, PhotoPicker.REQUEST_CODE);

    }

    /**
     * 保存录入的值
     *
     * @param editable
     * @param position
     */

    String testItmeVal = "";

    @Override
    public void OnItemName(Editable editable, int position) {

        ViseLog.d("***************" + position);
        if (allInspaction(position) != null) {
            testItmeVal = editable.toString();
            if (editable != null) {
                if (allInspaction(position).getInspactionitemBeen() != null) {
                    allInspaction(position).getInspactionitemBeen().setItemName(editable.toString());
                }
            }
        }
    }

    //检测名称
    @Override
    public void OnEditeValue(Editable editable, int position) {
        if (allInspaction(position) != null) {
            allInspaction(position).getInspactionitemBeen().setItemValue(editable.toString());
        }
    }

    //参考值
    @Override
    public void OnMsgCheck(String editable, int position) {
        if (allInspaction(position) != null) {
            allInspaction(position).getInspactionitemBeen().setStandardValue(editable.toString());
        }
    }

    //单位
    @Override
    public void OnUnit(Editable editable, int position) {
        if (allInspaction(position) != null) {
            allInspaction(position).getInspactionitemBeen().setDoseName(editable.toString());
        }
    }

    //是否为默认值
    @Override
    public void OnAttribute(int editable, int position) {
        if (allInspaction(position) != null) {
            allInspaction(position).getInspactionitemBeen().setAttribute(editable);
        }
    }

    //大项名称
    @Override
    public void OnInspectionName(Editable editable, String name, int position) {

//        isTitleName = editable.toString();
//        InspactionBean inspactionBean = itemAdapter.getData().get(position - 1);
//        inspactionBean.setInspactionName(1 + editable.toString());
//        ViseLog.d(position + "----" + editable.toString());
//
        if (name != null && name.length() > 0) {
            ViseLog.d("name" + isTitleName);
            isTitleName = "";
            InspactionBean inspaction = itemAdapter.getData().get(position - 1);
            inspaction.setInspactionName(name);
        } else {
            if (editable != null) {
                ViseLog.d("editable" + isTitleName);
                isTitleName = editable.toString();
                InspactionBean inspaction = itemAdapter.getData().get(position - 1);
                inspaction.setInspactionName(editable.toString());
            } else {
                isTitleName = "";
                InspactionBean inspaction = itemAdapter.getData().get(position - 1);
                inspaction.setInspactionName(name);
            }

        }

    }

    //获取列表所有数据
    public InspactionBean allInspaction(int position) {
        List<InspactionBean> inspactionBeenList = itemAdapter.getData();
        return inspactionBeenList.get(position - 1);

    }

    /**
     * 诊断信息
     */

    @ViewById(R.id.tv_proposal_doctor)
    TextView tv_proposal_doctor;
    @ViewById(R.id.tv_proposal)
    TextView tv_proposal;
    @ViewById(R.id.tv_diagnosis)
    LinearLayout tv_diagnosis;
    @ViewById(R.id.proposal)
    LinearLayout proposal;

    class Diagnosis implements UiInterface<AnotherResult<DiagnosisData>> {


        public Diagnosis(String recordTime) {
            //诊断信息
            diagnosisDataPresenter = new DiagnosisDataPresenter(this);
            diagnosisDataPresenter.PostDiagnosisData(recordTime);
        }

        @Override
        public void onViewSuccess(AnotherResult<DiagnosisData> data) {


            if (data.getList() == null || data.getList().size() == 0) {
                loadingbox.setVisibility(View.GONE);
                diagnosisbox.setVisibility(View.GONE);
                stamp.setVisibility(View.GONE);
            } else {
                if (data.getList() != null) {
                    int size = data.getList().size();
                    //诊断医生
                    String diagnosisDoctorx = null;
                    //建议医生
                    String proposalDoctor = null;
                    //诊断内容
                    StringBuffer stringBuffer = new StringBuffer();
                    //医生建议
                    StringBuffer buffer = new StringBuffer();
                    //医生建议
                    for (int i = 0; i < size; i++) {

                        //诊断内容
                        if (data.getList().get(i).getStatus() == 100) {
                            if (data.getList().get(i).getContent() != null) {
                                stringBuffer.append(data.getList().get(i).getContent() + ",");
                            }
                            //姓名
                            if (data.getList().get(0).getRelName() != null) {
                                diagnosisDoctorx = data.getList().get(i).getRelName() + "\t\t" + data.getList().get(0).getDiagnoseTime().substring(0, 10);
                            }
                        } else {
                            //医生建议
                            if (data.getList().get(i).getContent() != null) {
                                buffer.append(data.getList().get(i).getContent());
                            }
                            //建议医生名称
                            if (data.getList().get(i).getRelName() != null && data.getList().get(i).getRelName().length() > 0) {
                                proposalDoctor = data.getList().get(i).getRelName() + "\t\t" + data.getList().get(i).getDiagnoseTime().substring(0, 10);
                            }
                        }
                    }

                    //诊断内容
                    if (stringBuffer.toString().length() > 2) {
                        tv_diagnosis.setVisibility(View.VISIBLE);
                        if (diagnosisDoctorx != null && diagnosisDoctorx.length() > 0) {
                            doctorname.setText("医生\t" + diagnosisDoctorx + "诊断:");
                        }
                        note.setText(stringBuffer.toString().substring(0, stringBuffer.toString().length() - 1));
                    } else {
                        tv_diagnosis.setVisibility(View.GONE);
                    }

                    if (buffer.toString().length() > 0) {
                        proposal.setVisibility(View.VISIBLE);
                        tv_proposal.setText(buffer.toString());
                        if (proposalDoctor != null && proposalDoctor.length() > 0) {
                            tv_proposal_doctor.setText("医生\t" + proposalDoctor + "建议:");
                        }
                    } else {
                        proposal.setVisibility(View.GONE);
                    }

                    diagnosisbox.setVisibility(View.VISIBLE);
                    stamp.setVisibility(View.VISIBLE);
                }
            }
        }

        @Override
        public void onViewError(String msg) {
            loadingbox.setVisibility(View.GONE);
            if (msg != null) {
                msg(msg);
            }

        }

        @Override
        public void onViewRefreshUI() {
            loadingbox.setVisibility(View.GONE);
        }
    }


    /**
     * 获取单日化验单数据
     */
    class TestRecordInitDay implements UiInterface<AnotherResult<TestRecordData>> {

        private TestRecordInitPresenter testRecordInitPresenter;

        int stats;


        public TestRecordInitDay(String statsTime, int stats) {
            testRecordInitPresenter = new TestRecordInitPresenter(this);
            this.stats = stats;
            if (stats == 1) {
                testRecordInitPresenter.postLastDayInspection(statsTime);
            } else if (stats == 2) {
                testRecordInitPresenter.postNextDayInspection(statsTime);
            } else if (stats == 3) {
                testRecordInitPresenter.PostTestRecordInit(statsTime);
            }
        }


        @Override
        public void onViewSuccess(AnotherResult<TestRecordData> data) {
            //判断外层大项是否已经存在
            List<String> stList = new ArrayList<>();
            int size = data.getList().size();
            //判断若当前没有网络数据则加载本地数据库中数据
            if (size == 0) {
                if (stats == 2) {
                    datequery.nextfalseImage();
                } else if (stats == 1) {
                    datequery.lastfalseImage();
                } else if (stats == 3) {
//                    deleteList();
                    //初始化查询的时候对图片集合进行清除
                    deleteList();
                    mData.addAll(localData);

                    ViseLog.d("日期为空的时候获取的数据长度"+localData.size());
                    initAdapter(mData);
                }
            } else {
                deleteList();
                datequery.nextTrueImage();
                datequery.lastTrueImage();

                try {

                    Collections.sort(data.getList(), new Comparator<TestRecordData>() {
                        @Override
                        public int compare(TestRecordData o1, TestRecordData o2) {
                            if (o1.getParamValue() != null && o1.getParamValue().length() > 0 && o2.getParamValue() != null && o2.getParamValue().length() > 0) {
                                int date1 = Integer.parseInt(o1.getParamValue());
                                int date2 = Integer.parseInt(o2.getParamValue());
                                if (date1 > date2) {
                                    return 1;
                                }
                                return -1;
                            }
                            return 0;
                        }
                    });
                } catch (Exception e) {
                    ViseLog.d("数据排序异常" + e.getMessage());
                }


                // TODO: 2018/3/23  
                for (int i = 0; i < size; i++) {

                    //如果大项还不存在则新增
                    String inspectionName = data.getList().get(i).getInspectionName();
                    if (!stList.contains(inspectionName)) {

                        // 添加数据
                        stList.add(inspectionName);
                        mData.add(new InspactionBean(InspactionBean.TITLE, inspectionName));


                        //判断返回的数据时间只需要获取第一条数据即可
                        if (i == 0) {
                            String TimeDate = data.getList().get(0).getInspectionIndex().getTestTime();

                            //判断日期传过来的时间TestTime是不是空，不为空则表示从日历进来指定时间，上面日期直接显示TestTime
                            if (TestTime != null) {
                                datequery.setDate(TestTime);
                                diagnosis = new Diagnosis(TestTime);
                                ws_describe.setDate(TestTime);
                            } else {
                                datequery.setDate(TimeDate.substring(0, 10));
                                diagnosis = new Diagnosis(TimeDate.substring(0, 10));
                                ws_describe.setDate(TimeDate);
                            }
                            //获取诊断信息
//                            diagnosis = new Diagnosis(TimeDate, TimeDate);
                            //不适症状

                        }

                        for (int z = i; z < size; z++) {

                            if (data.getList().get(z).getInspectionName().equals(data.getList().get(i).getInspectionName())) {
                                InspactionitemBean inspactionitemBean = new InspactionitemBean();
                                inspactionitemBean.setItemName(data.getList().get(z).getItemName()); //保存化验小项名称
                                inspactionitemBean.setStandardValue(data.getList().get(z).getStandardValue().replaceAll("&lt;", "<")
                                        .replaceAll("&gt;", ">"));//保存化验小项参考值
                                //replaceAll("<br/>", "\n")
                                inspactionitemBean.setDoseName(data.getList().get(z).getDoseName());  //保存化验小项单位
                                inspactionitemBean.setParamValue(data.getList().get(z).getParamValue());  //附加值
                                inspactionitemBean.setOuterLayerItem(data.getList().get(i).getInspectionName());

                                String timeName = data.getList().get(z).getItemName();
                                if (timeName.equals("他克莫司")) {
                                    inspactionitemBean.setAttribute(data.getList().get(z).getAttribute());  //默认项 inspactionitemBean.setAttribute(ConstantManger.HIDEVIEW)
                                    inspactionitemBean.setIsHide("隐藏");
                                } else if (timeName.equals("环孢素谷浓度")) {
                                    inspactionitemBean.setAttribute(data.getList().get(z).getAttribute());  //默认项
                                    inspactionitemBean.setIsHide("隐藏");
                                } else if (timeName.equals("环孢素峰浓度")) {
                                    inspactionitemBean.setAttribute(data.getList().get(z).getAttribute());  //默认项
                                    inspactionitemBean.setIsHide("隐藏");
                                } else if (timeName.equals("西罗莫司")) {
                                    inspactionitemBean.setAttribute(data.getList().get(z).getAttribute());  //默认项
                                    inspactionitemBean.setIsHide("隐藏");
                                } else if (timeName.equals("霉酚酸酯")) {
                                    inspactionitemBean.setAttribute(data.getList().get(z).getAttribute());  //默认项
                                    inspactionitemBean.setIsHide("隐藏");
                                } else {
                                    inspactionitemBean.setAttribute(data.getList().get(z).getAttribute());  //默认项
                                }


                                if (datequery.getDate().equals(data.getList().get(0).getInspectionIndex().getTestTime().substring(0, 10))) {
                                    if (data.getList().get(z).getItemValue() != null && data.getList().get(z).getItemValue().length() > 0) {
                                        if (!data.getList().get(z).getItemValue().equals("0")) {
                                            if (data.getList().get(z).getItemValue().equals("0.0") || data.getList().get(z).getItemValue().equals("0.00")) {//检测到0.0置空
                                                inspactionitemBean.setItemValue("");
                                            } else {
                                                inspactionitemBean.setItemValue(data.getList().get(z).getItemValue());
                                            }
                                        } else {
                                            inspactionitemBean.setItemValue("");
                                        }
                                    } else {
                                        inspactionitemBean.setItemValue("");
                                    }

                                } else {
                                    inspactionitemBean.setItemValue("");
                                }
                                inspactionitemBean.setCriticalValue(""); //危机值

                                if (data.getList().get(i).getInspectionIndex() != null) {
                                    //判断当前数据是否为当日数据，如果不是时间不相等则id传空
                                    if (data.getList().get(i).getInspectionIndex().getTestTime().substring(0, 10).equals(datequery.getDate())) {
                                        inspactionitemBean.setId(data.getList().get(z).getId() + ""); //ID
                                    } else {
                                        inspactionitemBean.setId(""); //ID
                                    }
                                } else {
                                    inspactionitemBean.setId(""); //ID
                                }

                                //默认折叠
                                if (inspactionitemBean.getAttribute() != ConstantManger.DISPLAYVIEW) {
                                    //判断化验项目有检测值得话默认不进行隐藏
                                    if (inspactionitemBean.getItemValue() != null && inspactionitemBean.getItemValue().length() > 0) {
                                        inspactionitemBean.setIsHide("");
                                    } else {
                                        if (inspactionitemBean.getIsHide() != null && inspactionitemBean.getIsHide().length() > 0) {

                                            if (inspactionitemBean.getIsHide().equals("10")) {
                                                inspactionitemBean.setIsHide("");
                                            } else {
                                                inspactionitemBean.setIsHide("隐藏");
                                            }
                                        } else {
                                            inspactionitemBean.setIsHide("隐藏");
                                        }
                                    }
                                }

                                inspactionitemBean.setInspectionName(data.getList().get(z).getInspectionName());//大项名称
                                //如果检测项目为蛋白质则加载另外一个布局
                                if (data.getList().get(z).getItemName().contains("定性")) {
                                    mData.add(new InspactionBean(InspactionBean.PPOTEIN, inspactionitemBean));
                                } else if (data.getList().get(z).getItemName().equals("尿蛋白")) {
                                    mData.add(new InspactionBean(InspactionBean.PPOTEIN, inspactionitemBean));
                                } else {
                                    mData.add(new InspactionBean(InspactionBean.FROM, inspactionitemBean));
                                }
                            }
                        }

                        mData.add(new InspactionBean(InspactionBean.EDIT, true));
                    }
                }

                //获取图片并保存,如果化验单的时间不等于
                if (data.getList().get(0).getInspectionIndex().getTestTime().substring(0, 10).equals(datequery.getDate())) {
                    int num = data.getList().get(0).getPicList().size();
                    for (int p = 0; p < num; p++) {
                        minitDatas.add(new PhotoModel(RetrofitConnection.PHOTOURL + data.getList().get(0).getPicList().get(p).getCover()));
                    }
                    picListBeen.addAll(data.getList().get(0).getPicList());
                }
                //初始化布局
                initAdapter(mergeData(mData));
            }

            //加载医生添加的事件
            doctorEventPresenter.GetPatientSingleInspectionEventData(datequery.getDate(), datequery.getDate());

//            mergeData(mData);
        }

        @Override
        public void onViewError(String msg) {

        }

        @Override
        public void onViewRefreshUI() {
        }
    }

    //合并数据
    public List<InspactionBean> mergeData(List<InspactionBean> mMergeNetwork) {
        boolean isExists = false;
        if (localData == null || localData.size() == 0) {
            localData = MainAppliaction.getInstance().getInspactionBeanListDB();
        }
        //本地数据长度
        int localDataSize = localData.size();
        //网络数据长度
        int NetworkSize = mMergeNetwork.size();
        //循环本地数据
        for (int i = 0; i < localDataSize; i++) {
            if (localData.get(i).getInspactionitemBeen() == null) continue;
            isExists = false;
            // 循环网络数据

            int temp= -1;

            for (int a = 0; a < NetworkSize; a++) {
                if (mMergeNetwork.get(a).getInspactionitemBeen() == null) continue;

                //网络数据
                InspactionBean networkBean = mMergeNetwork.get(a);


                if (localData.get(i).getInspactionitemBeen().getItemName().equals(networkBean.getInspactionitemBeen().getItemName())) {
                    isExists = true;
                    temp = a;
                    break;
                }

            }

            if (isExists) {
                //update net item  //standard,boundary,critical
                //保存边界值
                mMergeNetwork.get(temp).getInspactionitemBeen().setBoundaryVal(localData.get(i).getInspactionitemBeen().getBoundaryVal());

                if (mMergeNetwork.get(temp).getInspactionitemBeen().getStandardValue() == null || mMergeNetwork.get(temp).getInspactionitemBeen().getStandardValue().length() == 0) {
                    mMergeNetwork.get(temp).getInspactionitemBeen().setStandardValue(localData.get(i).getInspactionitemBeen().getStandardValue());
                }

                mMergeNetwork.get(temp).getInspactionitemBeen().setCriticalValue(localData.get(i).getInspactionitemBeen().getCriticalValue());
            }
                else {
    //        add the local item  localData.get(i).getInspactionitemBeen()
                    mMergeNetwork.add(localData.get(i));
                }
        }

        ViseLog.d("保存的数据长度" + mMergeNetwork.size());

        return mMergeNetwork;
    }

    //对数据进行删除
    public void deleteList() {
        //对图片集合进行清除
        picListBeen.clear();
        photos.clear();
        minitDatas.clear();
        mData.clear();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //initData();

        //不适症状
        String time = datequery.getDate();
        ws_describe.setDate(time);
    }

    List<PhotoModel> photosModel = new ArrayList<>();

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != Activity.RESULT_OK)
            return;
        if (resultCode == this.RESULT_OK && requestCode == PhotoPicker.REQUEST_CODE) {
            if (data != null) {
                ArrayList<String> p = new ArrayList<>();
                p = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                photosModel.clear();
                for (int i = 0; i < p.size(); i++) {
                    PhotoModel photoModel = new PhotoModel();
                    photoModel.setOriginalPath(p.get(i));
                    photosModel.add(photoModel);
                }
                if (photosModel == null || photosModel.isEmpty()) {
                } else {
//                    minitDatas.clear();
                    photos.clear();
                    minitDatas.addAll(photosModel);
                    for (int i = 0; i < minitDatas.size(); i++) {
                        photos.add(minitDatas.get(i).getOriginalPath());
                    }
                    testGrideViewAdapter.notifyDataSetChanged();
                }
            }
        }

    }


    //图片上传
    public void upPhotoPath() {

        List<File> listFile = new ArrayList<>();
        listFile.clear();
        for (int i = 0; i < minitDatas.size(); i++) {
            if (!StringUtils.isUrl(minitDatas.get(i).getOriginalPath())) {
                listFile.add(new File(minitDatas.get(i).getOriginalPath()));
            }
        }

        ViseLog.d("提交的json数据", json);

        if (listFile.size() == 0) {
            RemindMedicine(errVal, json, "");
        } else {
            upPhoto(listFile);
        }
        testGrideViewAdapter.notifyDataSetChanged();
    }

    /**
     * 图片上传
     */

    public void upPhoto(List<File> listPath) {
        pictureConstant.PostPicture(listPath);
    }

    @Override
    public void updateInit(String path) {
        ViseLog.d("图片上传的地址" + path);
        CorePhone = path;
        RemindMedicine(errVal, json, CorePhone);
    }

    public void RemindMedicine(boolean errVal, String json, String corePath) {
        //获取当前选中的时间
        StringBuffer buffer = new StringBuffer();
        buffer.append(datequery.getDate());
        buffer.append(TimeZoneUtil.sdf.format(new Date()).substring(10, 19));

        if (errVal) {
            deleteGetRecentDiagnosePresenter.PostRemindMedicine(json, buffer.toString(), corePath, ConstantManger.NormalVal, datas);
        } else {
            deleteGetRecentDiagnosePresenter.PostRemindMedicine(json, buffer.toString(), corePath, ConstantManger.OutliersVal, datas);
        }
    }

    @Override
    public void onErrPhoto(String errVal) {
        if (pd != null) {
            pd.dismiss();
        }
        isClick = true;
        if (errVal != null) {
            msg("图片上传失败" + errVal);
        }
    }

    /**
     * 添加为布局
     */
    boolean testname = false;

    public void addFootView() {
        View view = getLayoutInflater().inflate(R.layout.head_view, (ViewGroup) rv_list.getParent(), false);
        final Button btn_divtest = (Button) view.findViewById(R.id.btn_divtest);

        //自定义化验单
        btn_divtest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (!testname) {
                    itemAdapter.getData().add(itemAdapter.getData().size() - 1, new InspactionBean(InspactionBean.EDIT, true));
                    InspactionBean inspactionBean = new InspactionBean();
                    inspactionBean.setItemType(InspactionBean.SUBMIT);
                    inspactionBean.setInspactionName("");
                    AddDivItem(itemAdapter.getData().size() - 1, inspactionBean);
                    testname = true;
                } else {
                    msg("请填写化验单信息");
                }

            }
        });
        itemAdapter.addFooterView(view);
    }

    //添加自定义项
    public void AddDivItem(int position, InspactionBean data) {

        itemAdapter.getData().add(position, data);
        itemAdapter.notifyItemInserted(position);//通知演示插入动画
        itemAdapter.remove(itemAdapter.getData().size() - 1);
        itemAdapter.notifyItemRangeChanged(position, itemAdapter.getData().size() - position);//通知数据与界面重新绑定
        itemAdapter.notifyDataSetChanged();
    }

    /**
     * 删除item 成功回调
     *
     * @param data
     */
    @Override
    public void onViewListenerSuccess(DataStateResult data) {
        if (data.getMsgCode().equals("0x00000000")) {
            msg("操作成功");
        }

    }

    /**
     * 删除失败
     *
     * @param msg
     */
    @Override
    public void onViewListenerError(String msg) {
        isClick = true;
        if (msg != null) {
            msg(msg);
        }
    }

    /**
     * 刷新界面
     */
    @Override
    public void onViewListenerRefreshUI() {
        isClick = true;
        testname=false;
    }

    @Override
    public void onViewTestRecordSuccess(DataStateResult data) {

        isClick = true;
        if (data.getMsgCode().equals("0x00000000")) {
            testItmeVal = "";
            msg("操作成功");
            String timeData = datequery.getDate();
            int stats = 3;//查询单日化验记录
            //提交后刷新界面
            testRecordInitDay = new TestRecordInitDay(timeData, stats);
            CorePhone = null;
        }
        pd.dismiss();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(UpdateEvent updateEvent) {

        if (updateEvent.type.equals(ConstantManger.ClosePhoto)) {
            //重新请求化验单数据
            ViseLog.d("日期" + datequery.getDate());
            testRecordInitDay = new TestRecordInitDay(datequery.getDate(), 3);
        }
    }


    //更改图片以后返回的图片地址
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(TestUpdatePhoto testUpdatePhoto) {
        if(testUpdatePhoto!=null){
            minitDatas.get(testUpdatePhoto.postion).setOriginalPath(testUpdatePhoto.urlpath);
            photos.set(testUpdatePhoto.postion,testUpdatePhoto.urlpath);
        }
        testGrideViewAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 利用环信提醒医生
     */

    PatientInfoData patientInfoData = MainAppliaction.getInstance().getPatient();

    public void SendMessage(DoctorListBean listBean) {

        String Datatime = datequery.getDate();
        ViseLog.d("医生的环信账号" + listBean.getRealName());
        StringBuffer buffer = new StringBuffer();
        buffer.append("[患者化验报告]\n");
        buffer.append("--------------------------------------------------\n");
        buffer.append(patientInfoData.getRealName() + " 添加了一个化验记录，并选择您为其诊断\n");
        buffer.append("化验日期:" + Datatime + "\n");
        buffer.append("--------------------------------------------------\n");
        buffer.append("以上为自动通知，如有疑问请及时回复。");
        EMMessage message = EMMessage.createTxtSendMessage(buffer.toString(), listBean.getBmobUserName());
        EMClient.getInstance().chatManager().sendMessage(message);
    }


    @Override
    public void DialogDetermine(List<DoctorListBean> data) {
        HashSet<String> joblist = new HashSet<String>();
        if (data != null) {
            for (int i = 0; i < data.size(); i++) {
                SendMessage(data.get(i));
                joblist.add(data.get(i).getId() + "");
            }

            //将返回的图片字符串进行逗号分隔
            if (joblist != null && joblist.size() != 0) {
                Iterator<String> iterator = joblist.iterator();
                while (iterator.hasNext()) {
                    datas += iterator.next() + ",";
                }
                datas = datas.substring(0, datas.length() - 1);
            }
            SubmitTestData();
        } else {
            SubmitTestData();
        }

        ViseLog.d(datas);
    }

    @Override
    public void Mydoctorx(AnotherResult<DoctorListBean> anotherResult) {
        if (anotherResult.getList() != null && anotherResult.getList().size() > 0) {
            choiceDoctorxDialog.show();
        } else {
            msg("请先去添加医生");
        }

    }

    String datas = "";

    /**
     * 查看医生添加的数据
     */
    @ViewById(R.id.tv_doctor_event)
    TextView tv_doctor_event;
    @ViewById(R.id.ll_layout_event)
    LinearLayout ll_layout_event;

    //事件查看
    @Click(R.id.tv_look_event)
    public void tv_look_event() {
        HistoryLifeActivity_.intent(this).start();
    }

    @Override
    public void onDoctorEventSuccess(AnotherResult<DoctorEventData> data) {
        Spanny spanny = new Spanny();
        ll_layout_event.setVisibility(View.GONE);
        if (data != null) {
            if (data.getList().size() > 0) {
                DoctorEventData doctorEventData = null;
                for (int i = data.getList().size() - 1; i >= 0; i--) {
                    if (data.getList().get(i).getIsHide() == 1) {
                        ViseLog.d("隐藏的事件内容" + data.getList().get(i).getIsHide());
                        doctorEventData = data.getList().get(data.getList().size() - 1);
                        break;
                    }
                }
                if (doctorEventData != null) {
                    spanny.append("医生\t", new ForegroundColorSpan(color(R.color.textcolor)));
                    spanny.append(doctorEventData.getRName(), new ForegroundColorSpan(color(R.color.default_blue_color)));
                    spanny.append("添加了一个事件", new ForegroundColorSpan(color(R.color.textcolor)));
                    tv_doctor_event.setText(spanny);
                    ll_layout_event.setVisibility(View.VISIBLE);
                }
            } else {
                ll_layout_event.setVisibility(View.GONE);
            }
        } else {
            ll_layout_event.setVisibility(View.GONE);
        }
    }

    private int color(int value) {
        return this.getResources().getColor(value);
    }

    @Override
    public void onDoctorEventError(String msg) {

    }

    @Override
    public void onDoctorEventRefreshUI() {

    }

    @Override
    public void onSuccessSameday(List<DailyItemInfodb> data) {

    }

    @Override
    public void onSubmitSuccess(DataStateResult dataStateResult) {

    }

    @Override
    public void onItemSuccess(DataStateResult dataStateResult) {

    }

    @Override
    public void ondeleteSuccess(DataStateResult dataStateResult) {

    }

    ChoiceDoctorxDialog choiceDoctorxDialog;

    @Override
    public void onDailyInspect(AnotherResult<DailyRecordDetailsData> dataAnotherResult) {
        if (dataAnotherResult.getList() != null && dataAnotherResult.getList().size() > 0) {
            choiceDoctorxDialog = new ChoiceDoctorxDialog(TestRecordActivity.this);
            choiceDoctorxDialog.setListener(TestRecordActivity.this);
        } else {
            msg("请完善日常记录");
            String time = datequery.getDate();
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append(time);
            stringBuffer.append(" 00:00:00");
            MoreRecodeActivity_.intent(this).TimeDate(stringBuffer.toString()).start();
        }
    }

    @Override
    public void onLineSuccess(AnotherResult<DailyRecordDetailsData> data) {

    }

    @Override
    public void onLineOneDaySuccess(AnotherResult<DailyRecordDetailsData> data) {

    }

    @Override
    public void onLastOneDaySuccess(AnotherResult<DailyRecordDetailsData> dataAnotherResult) {

    }

    @Override
    public void onNextOneDaySuccess(AnotherResult<DailyRecordDetailsData> dataAnotherResult) {

    }


    @Override
    public void LoseFocus(int position) {
        ViseLog.d("执行了");
        try {
            if (itemAdapter.getData().get(position) != null) {
                if (itemAdapter.getData().get(position).getItemType() != 3) {
                    itemAdapter.getData().remove(position - 1);
                }
            }
        } catch (Exception ex) {

            ViseLog.d("错误信息" + ex.getMessage());
        }

        if (rv_list.getScrollState() == RecyclerView.SCROLL_STATE_IDLE || (rv_list.isComputingLayout() == false)) {
            specialUpdate();
        }

    }


    private void specialUpdate() {
        Handler handler = new Handler();
        final Runnable r = new Runnable() {
            public void run() {
                itemAdapter.notifyDataSetChanged();
            }
        };
        handler.post(r);
    }

}
